package com.suliao.web.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suliao.common.base.PageFactory;
import com.suliao.common.base.Result;
import com.suliao.common.util.SessionUtil;
import com.suliao.home.entity.industry.*;
import com.suliao.home.entity.product.TypeDO;
import com.suliao.home.entity.product.UseDO;
import com.suliao.home.entity.supply.SupplyPictureDO;
import com.suliao.home.entity.sys.FileDO;
import com.suliao.home.service.industry.*;
import com.suliao.home.service.product.TypeService;
import com.suliao.home.service.product.UseService;
import com.suliao.home.service.supply.SupplyPictureService;
import com.suliao.home.service.sys.AreaService;
import com.suliao.home.service.sys.FileService;
import org.apache.dubbo.config.annotation.Reference;
import com.suliao.common.base.UserContext;
import com.suliao.common.util.CryPtoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 展品展示--控制层
 *
 * @author miao wenbin
 * @date 2020-12-17
 */
@Controller
@RequestMapping("/exhibitShow")
public class ExhibitShowController {

    @Autowired
    private SessionUtil sessionUtil;

    @Reference
    private ExhibitionBannerService exhibitionBannerService;

    @Reference
    private SupplyPictureService supplyPictureService;

    @Reference
    private ExhibitTypeService exhibitTypeService;

    @Reference
    private TypeService typeService;

    @Reference
    private TopicService topicService;

    @Reference
    private UseService useService;

    @Reference
    private ApplicationClassService applicationClassService;

    @Reference
    private CompanyExhibitorInformationService companyExhibitorInformationService;

    @Reference
    private FileService fileService;

    @Reference
    private AreaService areaService;

    private static String flag = null;
    private static String productTitle = null;
    private static String banPositionBack = null;

    /**
     * 展品首页
     * @param
     * @param province
     * @param city
     * @param district
     * @param page
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ModelAndView list(
            @RequestParam(value = "province",defaultValue = "") String province,
            @RequestParam(value = "city",defaultValue = "") String city,
            @RequestParam(value = "district",defaultValue = "") String district,
            @RequestParam(value = "productTitle",defaultValue = "")String productTitle,
            HttpServletRequest request,
            String banPositionBack,
            @RequestParam(value = "page",defaultValue = "") Integer page) {
        ModelAndView modelAndView=new ModelAndView("tradeShow/exhibits");
        modelAndView.addObject("productTitle",productTitle);
        modelAndView.addObject("banPositionBack",banPositionBack);

        // 获取登录人信息
        UserContext loginDoorUserDto = sessionUtil.getUserContext();
        if(loginDoorUserDto == null){
            System.out.println("----------");
        }else{
            Integer corpId = loginDoorUserDto.getCompanyId();
            //查询塑金余额
            String plasticGoldList = "0.00";
            if(corpId == null){
                modelAndView.addObject("plasticGoldList",plasticGoldList);
            }else{
              /*  EnterpriseInfoDto enterpriseInfoDto = new EnterpriseInfoDto();
                enterpriseInfoDto.setUuid(corpId);
                plasticGoldList = industryExhibitorService.findAllPlasticGolds(enterpriseInfoDto);
                modelAndView.addObject("plasticGoldList",plasticGoldList);*/
            }
        }
        modelAndView.addObject("province",province);
        modelAndView.addObject("city",areaService.getAreaName(city));
        modelAndView.addObject("district",areaService.getAreaName(district));
        //用于首页样式选中样式回显
        String ProductName = "展品";
        modelAndView.addObject("ProductName",ProductName);
        return modelAndView;
    }

    /**
     * 加载展品展示页面
     *
     * @return
     */
    @RequestMapping("/loadExhibitShow")
    public ModelAndView loadExhibitShow(Integer page, Integer id, HttpSession session) {
        ModelAndView mv = new ModelAndView("exhibitHall/exhibit_show");
        mv.addObject("productTitle", productTitle);
        mv.addObject("banPositionBack", banPositionBack);
        //分页
        Integer pageSize = 8;
        if ("".equals(page) || page == null) {
            page = 1;//显示首页
            pageSize = 8;//每页10项
        }

        //获取 展厅-展品展示-展厅banner 图片
        String postion = "产品展示";
        List<ExhibitionBannerDO> bannerList = exhibitionBannerService.getExhibitionHallbanner(id, postion);
        //判断banner位置的图片的数量是否为0，如果为0，则显示默认图片
        Integer pflag = 0;
        if (bannerList.size() > 0) {
            pflag = 1;
        } else {
            pflag = 0;
        }
        mv.addObject("pflag", pflag);
        mv.addObject("bannerList", bannerList);

        //获取展品列表 通过公司id 查询 图文描述
        Page<SupplyPictureDO> pageInfo = supplyPictureService.loadPageProductByCompanyId(PageFactory.createPageInfo(page, pageSize), id);
        List<SupplyPictureDO> pictureDtoList = pageInfo.getRecords();
        for (int i = 0; i < pictureDtoList.size(); i++) {
            String picUrlStr = pictureDtoList.get(i).getPictureExhibition();
            if (picUrlStr.indexOf(";") != -1) {
                String[] picOssUrlArr = picUrlStr.split(";");
                pictureDtoList.get(i).setPictureExhibition(picOssUrlArr[0]);
            }

        }

        mv.addObject("picDtoList", pictureDtoList);

        //初始化页面，页码数
        mv.addObject("pageNum", page);
        //获取所有的数据的条数
        Long allNum = pageInfo.getTotal(); // 总记录数
        mv.addObject("allNum", allNum);
        mv.addObject("pageS", pageInfo.getSize());

        //获取展品一级类型
        List<ExhibitTypeDO> classList = exhibitTypeService.getClassificationType(id);
        mv.addObject("classList", classList);
        mv.addObject("flag", flag);

        // 获取登录人信息
        String userInfo = (String) session.getAttribute("user-info");
        UserContext userContext = sessionUtil.getUserContext();
        mv.addObject("userinfo", userContext);
        if (userContext == null) {
            System.out.println("----------");
        } else {
            Integer companyId = userContext.getCompanyId();
            //查询塑金余额
            String plasticGoldList = "0.00";
            if (companyId == null) {
                mv.addObject("plasticGoldList", plasticGoldList);
            } else {
                   /* enterpriseInfoDto.setUuid(companyId);
                    plasticGoldList = industryExhibitorService.findAllPlasticGolds(enterpriseInfoDto);*/
                mv.addObject("plasticGoldList", plasticGoldList);
            }
        }

        //回显展厅标题名称
        mv.addObject("hallName", "产品展示");

        // 回显头部标题
        String banName = "产品展示";
        mv.addObject("banName", banName);
        mv.addObject("uuid", id);
        return mv;
    }

    /**
     * 通过一级分类的UUID去查询相应的展品列表
     */
    @RequestMapping("/getExhibitsById")
    public ModelAndView getExhibitsById(Integer exhibitTypeId, Integer companyId, Integer page, HttpSession session) {
        ModelAndView mv = new ModelAndView("exhibitHall/exhibit_show");
        mv.addObject("productTitle", productTitle);
        mv.addObject("banPositionBack", banPositionBack);
        //分页
        Integer pageSize = 8;
        if ("".equals(page) || page == null) {
            page = 1;//显示首页
            pageSize = 8;//每页10项
        }

        //获取 展厅-荣誉证书-展厅banner 图片
        String position = "产品展示";
        List<ExhibitionBannerDO> bannerList = exhibitionBannerService.getExhibitionHallbanner(companyId, position);
        //判断banner位置的图片的数量是否为0，如果为0，则显示默认图片
        Integer pflag = 0;
        if (bannerList.size() > 0) {
            pflag = 1;
        } else {
            pflag = 0;
        }
        mv.addObject("pflag", pflag);
        mv.addObject("bannerList", bannerList);


        //获取展品列表 通过公司id和展品分类id
        Page<SupplyPictureDO> pageInfo = supplyPictureService.loadPageProductByCompanyIdAndExhibitTypeId(PageFactory.createPageInfo(page, pageSize), companyId, exhibitTypeId);
        List<SupplyPictureDO> pictureList = pageInfo.getRecords();
        List<SupplyPictureDO> picDtoList = new ArrayList<>();


        //处理展品单个字段存放多个图片url的问题
        if (pictureList.size() > 0) {
            for (int i = 0; i < pictureList.size(); i++) {
                SupplyPictureDO pictureDto = pictureList.get(i);
                String picUrlStr = pictureDto.getPictureExhibition();
                if (picUrlStr.indexOf(";") == -1) {
                    picDtoList.add(pictureDto);
                } else {
                    String[] picOssUrlArr = picUrlStr.split(";");
                    SupplyPictureDO picDto = new SupplyPictureDO();
                    picDto.setPictureExhibition(picOssUrlArr[0]);
                    picDto.setProductId(pictureList.get(i).getProductId());
                    picDto.setPictureDescribe(pictureList.get(i).getPictureDescribe());
                    picDto.setProductTitle(pictureList.get(i).getProductTitle());
                    picDtoList.add(picDto);
                }
            }
        }

        mv.addObject("picDtoList", picDtoList);

        //初始化页面，页码数
        mv.addObject("pageNum", page);
        //获取所有的数据的条数
        Long allNum = pageInfo.getTotal(); // 总记录数
        mv.addObject("allNum", allNum);
        mv.addObject("pageS", pageInfo.getSize());

        //获取展品一级类型
        List<ExhibitTypeDO> classList = exhibitTypeService.getClassificationType(companyId);
        mv.addObject("classList", classList);

        mv.addObject("flag", flag);

        // 获取登录人信息
        String userInfo = (String) session.getAttribute("user-info");
        UserContext userContext = sessionUtil.getUserContext();
        mv.addObject("userinfo", userContext);
        if (userContext == null) {
            System.out.println("----------");
        } else {
            Integer newCompanyId = userContext.getCompanyId();
            //查询塑金余额
            String plasticGoldList = "0.00";
            if (newCompanyId == null) {
                mv.addObject("plasticGoldList", plasticGoldList);
            } else {
                   /* enterpriseInfoDto.setUuid(companyId);
                    plasticGoldList = industryExhibitorService.findAllPlasticGolds(enterpriseInfoDto);*/
                mv.addObject("plasticGoldList", plasticGoldList);
            }
        }

        //回显展厅标题名称
        mv.addObject("hallName", "产品展示");

        // 回显头部标题
        String banName = "产品展示";
        mv.addObject("banName", banName);
        mv.addObject("uuid", companyId);
        return mv;
    }

    // 展品页面局部刷新
    @RequestMapping(value = "/getProduct")
    @ResponseBody
    public Result getProduct(
            Integer customParentId,
            String customClassName,
            String topicName,
            String industryName,
            String province,
            String corpIdentities,
            String corpBusinessModel,
            String pageNum,
            String banPositionBack,
            String productTitle,
            String infoType) {
        Result result = Result.ok();
        try {
            Integer pageSize = 10;
            Integer pageNumber = Integer.valueOf(pageNum);
            pageNumber = (pageNumber == null || pageNumber == 0) ? 1 : pageNumber;
            Map res = new HashMap();
            // 面包屑
            List<TypeDO> newList = new ArrayList<>();
            if (customParentId != null) {
                TypeDO customClassDto = typeService.findById(customParentId);
                if (customClassDto == null) {
                    res.put("crumbsList", newList);
                } else {
                    int customLevel = customClassDto.getLevel();
                    if (customLevel == 1) {
                        newList.add(customClassDto);
                    } else if (customLevel == 2) {
                        TypeDO parentCustomDto = typeService.getById(customClassDto.getParentId());
                        newList.add(parentCustomDto);
                        newList.add(customClassDto);
                    } else if (customLevel == 3) {
                        TypeDO secondParentCustomDto = typeService.getById(customClassDto.getParentId());
                        TypeDO firstParentCustomDto = typeService.getById(secondParentCustomDto.getParentId());
                        newList.add(firstParentCustomDto);
                        newList.add(secondParentCustomDto);
                        newList.add(customClassDto);
                    }
                }
            }
            res.put("crumbsList", newList);

            // 获取产品分类信息
            List<TypeDO> industryCustomClassDtoList;
            if (customParentId == null) {
                // 一级分类
                industryCustomClassDtoList = typeService.customNames();
            } else {
                industryCustomClassDtoList = typeService.customName(customParentId);
                if (industryCustomClassDtoList.size() == 0) {
                    industryCustomClassDtoList = typeService.custom(customParentId);
                    for (int i = 0; i < industryCustomClassDtoList.size(); i++) {
                        Integer ParentId = industryCustomClassDtoList.get(i).getParentId();
                        industryCustomClassDtoList = typeService.customName(ParentId);
                    }
                } else {
                    industryCustomClassDtoList = typeService.customName(customParentId);
                }
            }
            Integer finalCategoryId = customParentId;
            boolean present = industryCustomClassDtoList.stream().filter(c -> finalCategoryId.equals(c.getId())).findAny().isPresent();
            if (!present) {
                customParentId = null;
            }
            res.put("industryCustomClassDtoList", industryCustomClassDtoList);
            // 获取主题专区信息
            List<TopicDO> industryTopicList = topicService.topicName();
            res.put("industryTopicList", industryTopicList);
            // 获取应用行业信息
            List<ApplicationClassDO> industryApplicationList = applicationClassService.applicationName();
            res.put("industryApplicationList", industryApplicationList);


            // 展品信息
            Page<CompanyExhibitorInformationVO> industryProductDtoList = companyExhibitorInformationService.pageIndustryProduct(PageFactory.createPageInfo(pageNumber, pageSize), province.substring(0, 2), customClassName, corpIdentities, corpBusinessModel, productTitle, topicName, industryName, infoType);
            res.put("pageList", industryProductDtoList.getRecords());
            // 当前页面总页数
            Long allNum = industryProductDtoList.getTotal();
            res.put("allNum", allNum);

            res.put("pageS", industryProductDtoList.getSize());
            res.put("pageNum", pageNum);
            // 展品图片
            if (industryProductDtoList.getRecords().size() > 0) {
                for (int i = 0; i < industryProductDtoList.getRecords().size(); i++) {
                    String fileId = industryProductDtoList.getRecords().get(i).getImageId();
                    //根据展品的UUID去查询相应的图片，用于展品展示
                    FileDO pictureDto = fileService.getFile(fileId);
                    String picUrlStr = pictureDto.getFileUrl();
                    if (picUrlStr.indexOf(";") == -1) {
                        industryProductDtoList.getRecords().get(i).setPictureExhibitionUrl(picUrlStr);
                    } else {
                        String[] picOssUrlArr = picUrlStr.split(";");
                        industryProductDtoList.getRecords().get(i).setPictureExhibitionUrl(picOssUrlArr[0]);
                    }
                }
            }

            res.put("industryProductDtoList", industryProductDtoList);

            res.put("customParentId", industryCustomClassDtoList.size() == 0 ? "" : customParentId);
            res.put("finalCategoryId", finalCategoryId);
            res.put("topicName", topicName);
            res.put("industryName", industryName);
            res.put("province", province);
            res.put("banPositionBack", banPositionBack);
            result.setData(res);
        } catch (Exception e) {
            result = Result.error("系统出错");
            e.printStackTrace();
        }
        return result;
    }

}
